package com.swufe.week6;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.params.HttpConnectionParams;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements Runnable {
    private  static  final  String TAG="MainActivity";
    EditText input;
    TextView result;
    private View btn;
    float dollarRate=0.15f;
    float euroRate=0.12f;
    float wonRate=172.0f;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        input=findViewById(R.id.rmb);
        result=findViewById(R.id.result);

        //获取share对象
        SharedPreferences sharedPreferences=getSharedPreferences("activity_main2",Activity.MODE_PRIVATE);

        dollarRate=sharedPreferences.getFloat("dollar_rate",0.0f);
        euroRate=sharedPreferences.getFloat("euro_rate",0.0f);
        wonRate=sharedPreferences.getFloat("won_rate",0.0f);

        Thread t=new Thread(this);
        t.start();

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what==5){
                    Bundle bdl = (Bundle) msg.obj;
                    dollarRate = bdl.getFloat("dollar-rate");
                    euroRate = bdl.getFloat("euro-rate");
                    wonRate = bdl.getFloat("won-rate");
                    Log.i(TAG, "handleMessage: dollarRate:" + dollarRate);
                    Log.i(TAG, "handleMessage: euroRate:" + euroRate);
                    Log.i(TAG, "handleMessage: wonRate:" + wonRate);
                    Toast.makeText(MainActivity.this, "汇率已更新", Toast.LENGTH_SHORT).show();
                }
                super.handleMessage(msg);
            }
        };


    }
    public void click(View btn){
        Log.d(TAG,"click");

        float r=0.0f;
        switch(btn.getId()){
            case R.id.btn_dollar:
               r=dollarRate;
               break;
            case R.id.btn_euro:
               r=euroRate;
               break;
            case R.id.btn_won:
               r=wonRate;
        }

        String str = input.getText().toString();
        Log.i(TAG,"click:str="+str);
        if(str==null||str.length()==0){
            Toast.makeText(this,"请输入金额",Toast.LENGTH_SHORT).show();
        }else{

            r=r*Float.parseFloat(str);
            result.setText(String.valueOf(r));
        }

        }
    public void open(View btn){
        this.btn = btn;
        Log.i(TAG, "open:...... ");
        Intent Main2Intent = new Intent(this, MainActivity2.class);

        Main2Intent.putExtra("dollar_rate_key",dollarRate);
        Main2Intent.putExtra("euro_rate_key",euroRate);
        Main2Intent.putExtra("won_rate_key",wonRate);

        Log.i(TAG, "openMain2Intent: dollarRate="+dollarRate);
        Log.i(TAG, "openMain2Intent: euroRate="+euroRate);
        Log.i(TAG, "openMain2Intent: wonRate="+wonRate);

        startActivityForResult(Main2Intent,5);
    }

    protected void onActivityResult(int requestCode, int resultCode,  Intent data) {
        if(requestCode==5&&resultCode==2){
            Bundle bundle=data.getExtras();
            dollarRate=bundle.getFloat("key_dollar",0.1f);
            euroRate=bundle.getFloat("key_euro",0.1f);
            wonRate=bundle.getFloat("key_won",0.1f);

            Log.i(TAG, "onActivityResult: dollarRate=" + dollarRate);
            Log.i(TAG, "onActivityResult: euroRate=" + euroRate);
            Log.i(TAG, "onActivityResult: wonRate=" + wonRate);

            //修改保存内容
            SharedPreferences sp=getSharedPreferences("activity_main2", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor=sp.edit();
            editor.putFloat("dollar_rate",dollarRate);
            editor.putFloat("euro_rate",euroRate);
            editor.putFloat("won_rate",wonRate);
            editor.apply();

        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void run() {
        Log.i(TAG, "run: .........");
        try{
            Thread.sleep(3000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        Bundle bundle = new Bundle();
        Document doc = null;
        try {
            String url = "http://www.usd-cny.com/bankofchina.htm";
            doc = Jsoup.connect(url).get();
            Log.i(TAG, "run: " + doc.title());
            Element tables = doc.getElementsByTag("table").first();
            Elements trs=tables.getElementsByTag("tr");
            for(Element tr:trs){
                Elements tds=tr.getElementsByTag("td");
                if(tds.size()>0){
                    Log.i(TAG, "run: td="+tds.first().text());
                    Log.i(TAG, "run: rate="+tds.get(5).text());
                   if(tds.get(0).text().equals("美元")){
                       dollarRate=100f/Float.parseFloat(tds.get(1).text());
                       Log.i(TAG, "run: dollar="+dollarRate);
                       bundle.putFloat("dollar-rate", dollarRate);
                   }
                    if(tds.get(0).text().equals("欧元")){
                        euroRate=100f/Float.parseFloat(tds.get(1).text());
                        Log.i(TAG, "run: euro="+euroRate);
                        bundle.putFloat("euro-rate", euroRate);
                    }
                    if(tds.get(0).text().equals("韩元")){
                        wonRate=100f/Float.parseFloat(tds.get(1).text());
                        Log.i(TAG, "run: won="+wonRate);
                        bundle.putFloat("won-rate", wonRate);
                    }

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回给主线程
        Message msg = handler.obtainMessage(5);
        msg.obj = bundle;
        handler.sendMessage(msg);
        
    }

    private String inputStream2String(InputStream inputStream) throws IOException{
            final  int bufferSize=1024;
            final  char[] buffer=new char[bufferSize];
            final  StringBuilder out=new StringBuilder();
            Reader in =new InputStreamReader(inputStream,"gb2312");
            while (true){
                int  rsz=in.read(buffer,0,buffer.length);
                if (rsz<0)
                    break;
                out.append(buffer,0,rsz);
            }
            return out.toString();
        }
    }
